(function() {
	require(['jquery', 'box', 'bootstrapTable', 'confirm', 'html2canvas', 'jspdf'], function(jquery,box) {
		
		var audit = $('#contentNav').data('auditState'),
			reportId = audit['reportId'], type = audit['type'], //check:查看， edit：编辑
			auditArr = audit['auditArr'] || [], auditArrLen = auditArr.length;
		
		if(type == 'edit') {
			if(auditArrLen == 0) {
				//首次填写申报表
				//创建一个审核表
				initTable();
				initAuditCommit();
				//绑定优，良，中，差选中事件
				bindGetUlList();
				//绑定提交事件,在if外，统一做绑定
			} else if(auditArrLen > 0) {
				//编辑申报表，相当于更新操作
				initTableWithData(auditArr[0], getLis);
				//向页面中插入按钮
				initAuditCommit();
				//绑定优，良，中，差选中事件
				bindGetUlList();
				//绑定提交事件,在if外，统一做绑定
			}
			//绑定提交事件
			bindClickEvent('auditCommit', {
				reportId: reportId,
				resetFun: reset,
				saveFun: save,
				commitFun: commit,
				ajaxCommitFun:ajaxCommit,
				ajaxSaveFun: ajaxSave,
				getSelectedObj: getSelectedObj,
				getSelected: getSelected,
				initTableWithData: initTableWithData,
				getLis: getLis,
				listData: auditArr[0]
			}, AuditCommit);
			
		}else if(type == 'check') {
			//直接生成查看表
			if(auditArrLen > 0) {
				initTableWithData(auditArr[0], getLis);
			}
			
		}else {
			$.alert({title: '提示', content: "出现了其他情况，开发人员查看"});
		}
		
		//插入审核表当中的优，良，中，差：四个选项
		function initTable() {
			var ulObjs = $('table .evaluate'), i=0, len = ulObjs.length,
			constantsArr = ['specificationIntegrity', 'clearClarity', 'targetCorrelation',
					        'indicatorsOfScientific', 'performanceLegitimacy', 'fundsFit',
					        'implementationPossibility', 'conditionsOfAdequacy', 'comprehensiveRating'];
			if(len != constantsArr.length) {
				return;
			}
			for(i=0; i<len; i++) {
				$ulObj = $(ulObjs[i]);
				$ulObj.attr('data-name', constantsArr[i]);
				$ulObj.append(getLis());
			}
		}
		
		//初始化提交按钮，给页面添加提交按钮
		function initAuditCommit() {
			$('#auditCommit').append(
					'<button   type="button" class="btn btn-sm audit-but" data-type="reset">重置</button>'
			  		+ '<button type="button" class="btn btn-sm audit-but" data-type="save">保存</button>'
			  		+ '<button type="button" class="btn btn-sm audit-but" data-type="commit">提交</button>');
		}
		
		
		//绑定点击事件，使得优、良、中、差选中
		function bindGetUlList() {
			$('table').bind('click', function(evt) {
				var target = evt.target, tagName = target.tagName, $t = $(target), targetCls = $t.attr('class'),
					li = $t.parent(), ul = $(li).parent(), selected = "selected", flag=-1, liCls = "";
				if(tagName != "A" || targetCls != "audit"){
					return;
				}
				liCls = $(li).attr('class') || "";
				if(liCls.indexOf(selected)>flag) {
					return;
				} else {
					clearSelected(ul);
					$(li).attr('class', selected);
				}
			});
		}
		
		//绑定点击事件
		function bindClickEvent(id, data, fun) {
			$('#' + id).unbind('click').bind('click', data, fun);
		}
		
		//绑定重置，保存，提交事件
		function AuditCommit(evt) {
			var dataList = evt.data,
				reportId = dataList.reportId,
				resetFun = dataList.resetFun,
				saveFun = dataList.saveFun,
				commitFun = dataList.commitFun,
				getSelectedObjFun = dataList.getSelectedObj,
				getSelectedFun = dataList.getSelected,
				ajaxCommitFun = dataList.ajaxCommitFun,
				ajaxSaveFun = dataList.ajaxSaveFun,
				initTableWithData = dataList.initTableWithData,
				getLis = dataList.getLis,
				listData = dataList.listData,
				target = evt.target, tagName = target.tagName, $t = $(target),
				type = $t.attr('data-type'), reset = "reset", save = "save",
				commit = "commit";
			if(tagName != "BUTTON") {
				return;
			}
			switch(type) {
				case reset:
					resetFun(initTableWithData, getLis, listData);
					break;
				case save:
					saveFun(reportId, ajaxSaveFun, getSelectedFun);
					break;
				case commit:
					commitFun(reportId, ajaxCommitFun, getSelectedFun);
					break;
				default:
					break;
			}
		}
		
		function reset(initTableWithData, getLis, listData) {
			$.ajax({
				url: 'audit/retrieveAuditByReportId.service',
				type: 'post',
				data: {reportId: reportId},
				success: function(data) {
					var result = data.data;
					if(result != null && data.success) {
						initTableWithData(result, getLis);
					} else {
						$.alert({
							title: '提示',
							content: "重置有误，请关闭后重试！"
						});
					}
				}
			});
		}
		
		function save(reportId, ajaxSaveFun, getSelected) {
			var submitObj = {};
			if(getSelectedObj(submitObj, "0",getSelected)) {
				submitObj['reportId'] = reportId;
				submitObj['id'] = $('#auditId').val();
				submitObj['overallComments'] = $('#overallComments').val();
				//给obj添加一个状态：保存
				submitObj['stateOFAuditTable'] = '0'; //
				ajaxSaveFun(submitObj, auditArr);
			}
		}
		
		function commit(reportId, ajaxCommitFun, getSelected) {
			var submitObj = {};
			if(getSelectedObj(submitObj, "1", getSelected)) {
				submitObj['reportId'] = reportId;
				submitObj['id'] = $('#auditId').val();
				submitObj['overallComments'] = $('#overallComments').val();
				//给obj添加一个状态：提交
				submitObj['stateOFAuditTable'] = '1'; 
				ajaxCommitFun(submitObj, auditArr);
			}
		}
		
		function ajaxSave(obj, auditArr) {
			$.ajax({
				url: 'audit/auditSave.service',
				type: 'post',
				data: obj,
				success: function(data) {
					var resultData = data.data || null;
					if(resultData != null && data.success) {
						$('#auditId').val(resultData.id);
						$.alert({title: '提示',content: '保存已成功'});
						$.ajax({
							url:"report/retrieveReportForDOPAF.service",
							type:"post",
							data: {},
							success: function(data) {
								$('#audit_list').data('$table').bootstrapTable('load', data.data);
							}
						});
					} else {
						$.alert({title: '提示', content: data.errorMsg});
					}
				}
			});
		}
		
		function ajaxCommit(obj, auditArr) {
			$.ajax({
				url: 'audit/auditSave.service',
				type: 'post',
				data: obj,
				success: function(data) {
					var resultData = data.data || null;
					if(resultData != null && data.success) {
						$('#auditId').val(resultData.id);
						$('#subContent').data('modal').modal('hide');
						$.alert({title: '提示',content: '提交成功'});
						$.ajax({
							url:"report/retrieveReportForDOPAF.service",
							type:"post",
							data: {},
							success: function(data) {
								$('#audit_list').data('$table').bootstrapTable('load', data.data);
							}
						});
					} else {
						$.alert({title: '提示',content: data.errorMsg});
					}
				}
			});
		}
		
		function getSelectedObj(obj, state, getSelected) {
			var $uls = $('table .evaluate'), i=0, len = $uls.length, ul = {}, tempObj = {},
				auditObj = {'specificationIntegrity': '规范完整性', 'clearClarity': '明确清晰性',
							'targetCorrelation': '目标相关性', 'indicatorsOfScientific': '指标科学性',
							'performanceLegitimacy': '绩效合理性', 'fundsFit': '资金匹配性',
					        'implementationPossibility': '实现可能性', 'conditionsOfAdequacy': '条件充分性',
					        'comprehensiveRating': '综合评定等级'};
			if(state == "0") {
				for(i=0; i<len; i++) {
					ul = $uls[i];
					tempObj = getSelected(ul);
					obj[tempObj.name] = tempObj.value;
				}
			} else if(state == "1"){
				for(i=0; i<len; i++) {
					ul = $uls[i];
					tempObj = getSelected(ul);
					if(tempObj.value != "") {
						obj[tempObj.name] = tempObj.value;
					} else {
						$.alert({title: '提示', content: auditObj[tempObj.name] + "没有评审，不能提交"});
						return false;
					}
				}
			}
			return true;
		}
		
		function getSelected(ulObj) {
			var $obj = $(ulObj), name = $obj.attr('data-name'), value = "",
				liObjs = $obj.children(), len = liObjs.length, cls = "",
				liObj = {}, i=0, selected="selected", flag=-1;
			
			for(i=0; i<len; i++) {
				liObj = $(liObjs[i]);
				cls = liObj.attr('class') || "";
				if(cls.indexOf(selected)>flag) {
					value = liObj.attr('data-name');
					return {'name': name, 'value': value};
				}
			}
			return {'name': name, 'value': ""};
		}
		
		//查看审核过的审核表
		function initTableWithData(data, getLis){
			var ulObjs = $('table .evaluate'), i=0, len = ulObjs.length,
				constantsArr = ['specificationIntegrity', 'clearClarity', 'targetCorrelation',
						        'indicatorsOfScientific', 'performanceLegitimacy', 'fundsFit',
						        'implementationPossibility', 'conditionsOfAdequacy', 'comprehensiveRating'];
			if(len != constantsArr.length) {
				return;
			}
			for(i=0; i<len; i++) {
				$ulObj = $(ulObjs[i]);
				$ulObj.attr('data-name', constantsArr[i]);
				$ulObj.empty().append(getLis(data[constantsArr[i]]));
			}
			$('#overallComments').val(data['overallComments']);
			$('#auditId').val(data['id']);
		}
		
		function getLis(index) {
			if(index != "" && index != null && index != "undefined") {
				var i = 0, arr = ["优", "良", "中", "差"], strArr = [];
				for(i=0; i<4; i++) {
					if(index == i) {
						strArr.push('<li class="selected" data-name="' + i + '"><a class="audit" href="javascript: void(0)">' + arr[i] + '</a></li>');
					} else {
						strArr.push('<li data-name="' + i + '"><a class="audit" href="javascript: void(0)">' + arr[i] + '</a></li>');
					}
				}
				return strArr.join('');
			} else {
				return '<li data-name="0"><a class="audit" href="javascript: void(0)">优</a></li>'
		    			+ '<li data-name="1"><a class="audit" href="javascript: void(0)">良</a></li>'
		    			+ '<li data-name="2"><a class="audit" href="javascript: void(0)">中</a></li>'
		    			+ '<li data-name="3"><a class="audit" href="javascript: void(0)">差</a></li>';
			}
		}
		
		//清除选中的所有优良中差
		function clearSelected(ul) {
			var lis = $(ul).children(), i=0, len = lis.length;
			for(i=0; i<len; i++) {
				$(lis[i]).removeClass('selected');
			}
		}
		
		/*导出按钮-- 生成PDF*/
		$('#config_out_sure').click(function () {
			var pdf = new jsPDF('p', 'pt', 'letter'), 
			source = document.getElementById('subTable'),
			/*specialElementHandlers = {
				'#bypassme': function(element, renderer){
					return true
				}
			}*/
			margins = {
			    top: 80,
			    bottom: 60,
			    left: 40,
			    width: 522
			  };
			pdf.fromHTML(
				document.getElementById('subTable'), 
			  	margins.left, 
			  	margins.top, 
			  	{
			  		'width': margins.width, 
			  		//'elementHandlers': specialElementHandlers
			  	},
			  	function (dispose) {
			  	  pdf.save('report_pdf_' + new Date().getTime() + '.pdf');
			      },
			  	margins
			  )
		});
		
	});
})();